var rkshstock = {
    fillData:function () {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm':'cd'}, function (cddata) {
            $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm':'jzfs'}, function (data) {
                fillHtmxByCgd($.webPath() + '/kcgl/rksh/rksh_cgmx?rksh.id=' + $("[name='rksh.id']").val() || '', cddata, data);
            })
        });
    }
}

//采购单明细
function fillHtmxByCgd(href, cdOptions, fsOptions) {
    $("#rksh_rk_mx").edatagrid({
        url:href,
        fitColumns:false,
        singleSelect:true,
        fit:false,
        height:180,
        checkOnSelect:false,
        selectOnCheck:false,
        rownumbers:true,
        toolbar:"#rksh_cgdmx_toolbar",
        frozenColumns:[
            [
                {field:'wzgg.code', title:'物资编码', width:120, align:'center', rowspan:2},
                {field:'wzgg.name', title:'物资名称', width:50, align:'center', rowspan:2},
                {field:'wzgg.ggxh', title:'规格型号', width:50, align:'center', rowspan:2},
                {field:'wzgg.th', title:'图号', width:50, hidden:true},
                {field:'cd.z', title:'产地', width:50, align:'center', rowspan:2},
                {field:'jzfs.id', align:'center', editor:{type:'combobox', options:{
                    data:fsOptions,
                    valueField:'id',
                    textField:'z',
                    multiple:false,
                    panelHeight:'55'
                }
                }, formatter:function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].z;
                    }
                    return value;
                }, title:'记重方式', width:50, align:'center', rowspan:2}
            ]
        ],
        columns:[
            [
                {title:'发货', colspan:2},
                {title:'到货', colspan:3},
                {field:'kh.id', title:'卡号ID', hidden:true},
                {field:'kh.khbm', title:'卡号编码', align:'center', hidden:true},
                {field:'hsj', title:'含税价', align:'right', width:120, rowspan:2,
                    formatter:function (value) {
                        var val = formatJeForHtml(value);
                        return val;
                    }},
                {field:'bhsj', title:'不含税价', align:'right', width:120, rowspan:2,
                    formatter:function (value) {
                        var val = formatJeForHtml(value);
                        return val;
                    }}
            ],
            [

                {field:'js', title:'件数', precision:4, align:'right', width:50},
                {field:'sbsl', title:'数量', precision:4, width:120, align:'right',
                    formatter:function (value) {
                        var val = formatSlForHtml(value);
                        return val;
                    }},
                {field:'rkjs', title:'件数', width:50, align:'right'},
                {field:'rkjz', title:'件重', width:50, align:'right'},
                {field:'rksl', title:'数量', width:120, align:'right',
                    formatter:function (value) {
                        var val = formatSlForHtml(value);
                        return val;
                    }}
            ]
        ],
        onSelect:function (rowIndex, rowData) {
            //获取每个单元格
            $("#rksh_dhd_mx").datagrid('unselectAll');
            $("#rksh_dhd_mx").datagrid('reload', {cgdmxId:rowData.id});
        }
    })

    //到货单明细
    $("#rksh_dhd_mx").datagrid({
        url:$.webPath() + '/kcgl/dhd/dhdList?cgdId=' + $("[name='rksh.id']").val(),
        fitColumns:true,
        singleSelect:true,
        fit:false,
        height:180,
        checkOnSelect:false,
        selectOnCheck:false,
        rownumbers:true,
        toolbar:"#rksh_dhdmx_toolbar",
        columns:[
            [
                {field:'id', title:'ID', hidden:true},
                {field:'cgdmxId', title:'采购单明细ID', hidden:true},
                {field:'dhrq', title:'到货日期', width:47, align:'center'},
                {field:'wz.code', title:'物资编码', width:47, align:'center'},
                {field:'wz.name', title:'物资名称', width:30, align:'center'},
                {field:'wz.ggxh', title:'规格型号', width:30, align:'center'},
                {field:'wz.dw', title:'单位', width:20, align:'center'},
                {field:'cd', title:'产地', width:30, align:'center'},
                {field:'js', title:'件数', width:50, align:'right'},
                {field:'cz', title:'称重', width:50, align:'center'},
                {field:'sssl', title:'实收数量', width:100, align:'right',
                    formatter:function (value) {
                        var val = formatSlForHtml(value);
                        return val;
                    }},
                {field:'ysjl', title:'验收结论', width:50, align:'center'},
                {field:'zt', title:'状态', width:30, align:'center',
                    formatter:function (value) {
                        if (value == 'ybc') {
                            return '已保存';
                        } else if (value == "yys") {
                            return '已验收';
                        }
                    }
                }
            ]
        ],
        onSelect:function (rowIndex, rowData) {
            $("#rksh_rk_mx").edatagrid('unselectAll');
            if (rowData.zt == "ybc") {
                $("#btn_rksh_del_dhd").show();
                $("#btn_rksh_validate_dhd").show();
                $("#btn_rksh_update_dhd").show();
            } else if (rowData.zt == "yys") {
                $("#btn_rksh_del_dhd").hide();
                $("#btn_rksh_update_dhd").hide();
                $("#btn_rksh_validate_dhd").hide();
            }
        },
        onLoadSuccess:function () {
            sumToEdithor();
        },
        onDblClickCell:function (index, field, value) {
            if (field == "dhrq") {
                var record = $("#rksh_dhd_mx").datagrid("getSelected")
                if (record.zt == "ybc") {
                    validate_modify('验收到货单', 'update_dhd');
                } else if (record.zt == "yys") {
                    validate_sreach("到货单信息");
                }
            }
        }
    })

}

$(function () {
    rkshstock.fillData();
    setTimeout(function () {
        $('#rksh_dhd_tabs').tabs('select', "入库明细");
    }, 100);


    //删除按钮触发-删除选中的到货单
    $('#btn_rksh_del_dhd').click(function () {
        var dhd_del_row = $('#rksh_dhd_mx').datagrid('getSelected');
        var messages = "是否确认删除此到货单";
        if (dhd_del_row) {
            $.messager.confirm('确认', messages, function (r) {
                if (r) {
                    $.ajax({
                        url:$.webPath() + "/kcgl/dhd/delete_dhd",
                        dataType:'json',
                        type:'POST',
                        data:{dhdId:dhd_del_row.id},
                        success:function (data) {
                            if (data.statusCode == 200) {
                                $.messager.show({
                                    title:'提示框',
                                    msg:data.message,
                                    timeout:3000,
                                    showType:'slide'
                                });
                                $('#rksh_dhd_mx').datagrid('reload');
                            } else {
                                $.messager.alert('提示', data.message, 'info');
                            }
                        }
                    });
                }
            });
        } else {
            $.messager.alert('提示', '请先选择到货单', 'info');
        }
    });

    //全部入库按钮触发
    $('#btn_rkshMx_allSave_dhd').click(function () {
        rksh.win_rksh.mask();
//        $('#rksh_rk_mx').edatagrid('acceptChanges');
//        var rk_datas = $('#rksh_rk_mx').edatagrid('getData');
//        var errorIndex = "";
//        $.each(rk_datas.rows, function (i, val) {
//            if (val.sbsl != val.rksl) {
//                errorIndex += (i + 1) + ',';
//            }
//        })
//        errorIndex = errorIndex.substring(0, errorIndex.length - 1);
//        if (errorIndex != "") {
//            $.messager.confirm('确认', '第' + (errorIndex) + '行的到货数量与发货数量不符是否要继续入库', function (r) {
//                if (r) {
//                    rksh_stock();
//                }else{
//                    rksh.win_rksh.mask('hide');
//                }
//            });
//        } else {
//            rksh_stock();
//        }
    });

    //新增按钮
    $("#btn_rksh_add_dhd").click(function () {
        dhd_add('新增到货单', 'add_dhd');
    });
    //修改按钮
    $("#btn_rksh_update_dhd").click(function () {
        dhd_modify('修改到货单', 'update_dhd');
    });
    //验收按钮触发
    $("#btn_rksh_validate_dhd").click(function () {
        validate_modify('验收到货单', 'update_dhd');
    });
})

//新增到货单
function dhd_add(title, action) {
    var rkMx_row = $('#rksh_rk_mx').datagrid('getSelected');
    if (rkMx_row) {
        var rkshId = $("[name='rksh.id']").val();
        var wzCode = rkMx_row['wzgg.code'] == null ? '' : rkMx_row['wzgg.code'];
        var wzName = rkMx_row['wzgg.name'] == null ? '' : rkMx_row['wzgg.name'];
        var wzGgxh = rkMx_row['wzgg.ggxh'] == null ? '' : rkMx_row['wzgg.ggxh'];
        var dw = rkMx_row['wzgg.dw'] == null ? '' : rkMx_row['wzgg.dw'];
        var cd = rkMx_row['cd.z'] == null ? '' : rkMx_row['cd.z'];
        var sbsl = rkMx_row.sbsl - sumYssl();
        var data = {type:"add", cgdmxId:rkMx_row.id, rkshId:rkshId, wzId:rkMx_row['wzgg.id'], wzCode:wzCode, wzName:wzName, wzGgxh:wzGgxh, dw:dw, cd:cd, yssl:sbsl};
        var href = $.webPath() + "/kcgl/dhd/rksh_dhd_content";
        var actionUrl = $.webPath() + "/kcgl/dhd/" + action;
        dhd_showDialog(title, href, actionUrl, data);
    } else {
        $.messager.alert('提示', '请先选择一条采购单明细', 'info');
    }

}

//修改到货单
function dhd_modify(title, action) {
    var record = $("#rksh_dhd_mx").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要修改的到货单！", "warning");
        return;
    }
    var rkshId = $("[name='rksh.id']").val();
    var data = {type:"add", dhdId:record.id, rkshId:rkshId};
    var href = $.webPath() + "/kcgl/dhd/rksh_dhd_content";
    var actionUrl = $.webPath() + "/kcgl/dhd/" + action;
    dhd_showDialog(title, href, actionUrl, data);
}

//验收到货单
function validate_modify(title, action) {
    var record = $("#rksh_dhd_mx").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要修改的到货单！", "warning");
        return;
    }
    var rkshId = $("[name='rksh.id']").val();
    var data = {type:"val", dhdId:record.id, rkshId:rkshId};
    var href = $.webPath() + "/kcgl/dhd/rksh_dhd_content";
    var actionUrl = $.webPath() + "/kcgl/dhd/" + action;
    dhd_showDialog(title, href, actionUrl, data);
}

//查询到货单信息的方法
function validate_sreach(title) {
    var record = $("#rksh_dhd_mx").datagrid("getSelected");
    var rkshId = $("[name='rksh.id']").val();
    var data = {type:"val", dhdId:record.id, rkshId:rkshId};
    var href = $.webPath() + "/kcgl/dhd/rksh_dhd_detail";
    dhd_showDetailDialog(title, href, data);
}
//查询到货单验收信息弹出窗口
function dhd_showDetailDialog(title, href, data) {
    var win = $.window({
        title:title,
        width:800,
        height:500,
        cache:false,
        url:href,
        data:data,
        modal:true
    });
}
//新增或修改弹出窗口
function dhd_showDialog(title, href, actionUrl, data) {
    var win = $.window({
        title:title,
        width:900,
        height:500,
        cache:false,
        url:href,
        data:data,
        modal:true,
        buttons:[
            {
                text:'保存',
                handler:function () {
                    $(win).mask();
                    $('#dhd_Form').form('submit', {
                        url:actionUrl,
                        onSubmit:function () {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                $(win).mask('hide');
                                return false;
                            }
                            return isValid;
                        },
                        success:function (data) {
                            $(win).mask('hide');
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                $('#rksh_dhd_mx').datagrid('reload');
                                $.messager.show({
                                    title:'提示',
                                    msg:json.message,
                                    timeout:3000,
                                    showType:'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}

//全部入库调用方法
function rksh_stock() {
    $("#rksh_rk_mx").edatagrid('saveRow');
    $("#rksh_cgd_Form").form('submit', {
        url:$.webPath() + "/kcgl/rksh/stock_rksh",
        onSubmit:function (param) {
            var data = $('#rksh_rk_mx').edatagrid("getData");
            if (!data.rows.length) {
                $('#rksh_cgd_Form').tabs('select', "采购明细");
                $.messager.alert("提示", "采购明细需要填写!", "waring");
                return false;
            }
            var arrayPrefix = 'rksh.cgdmxList';
            //物资计划明细
            var paramString = "{";
            //物资计划明细
            for (var i = 0; i < data.rows.length; i++) {
                if (data.rows[i].sbsl != 0 && data.rows[i].rksl == 0) {
                    $.messager.alert('提示', '第' + (i + 1) + '行的入库数量不能为0', 'info');
                    return false;
                }
                {
                    var objectString = $.toJSONStringSubPrefix(data.rows[i], arrayPrefix + "[" + i + "].",
                        [
                            'id',
                            ['wzgg.id', 'gg.id'],
                            'cd.id',
                            'jzfs.id',
                            'hsj',
                            'bhsj',
                            'bz',
                            'sbsl',
                            'js',
                            'rksl',
                            'rkjs',
                            'rkjz',
                            ['kh.id', 'kh.id']
                        ]);
                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                }
            }
            if (data.rows && data.rows.length > 0)
                paramString = paramString.substring(0, paramString.length - 1);
            paramString += "}";
            $.extend(param, $.parseJSON(paramString));
            return $(this).form('validate');
        },
        success:function (data) {
            rksh.win_rksh.mask('hide');
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                $(rksh.win_rksh).window('close');
                $('#grid_rksh').datagrid('reload');
                $('#layout_rksh').layout('panel', 'center').panel('refresh');
                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
            } else if (obj.statusCode == "300") {
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}

//计算计划总量
function countSum(grid, name, idVal) {
    var sumje = 0;
    var data = $(grid).datagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        if (data.rows[i]['cgdmxId'] == idVal) {
            var je = parseFloat(data.rows[i][name]);
            je = isNaN(je) ? 0 : je;
            sumje += je;
        }
    }
    return sumje;
}

function sumToEdithor() {
    var rk_data = $('#rksh_rk_mx').edatagrid('getData');
    var dhd_data = $('#rksh_dhd_mx').datagrid('getData');
    var index;
    $.each(rk_data.rows, function (i, val) {
        $.each(dhd_data.rows, function (j, dhdVal) {
            if (val.id == dhdVal.cgdmxId) {
                index = $("#rksh_rk_mx").edatagrid('getRowIndex', val);
                var sssl = countSum('#rksh_dhd_mx', 'sssl', val.id);
                var cz = countSum('#rksh_dhd_mx', 'cz', val.id);
                var js = countSum('#rksh_dhd_mx', 'js', val.id);
                val.rksl = sssl;
                val.rkjs = js;
                val.rkjz = cz;
                $('#rksh_rk_mx').edatagrid('refreshRow', index);
                $("#rksh_rk_mx").datagrid('endEdit', index);
            }
        });
    });
    $("#rksh_rk_mx").datagrid('beginEdit', index);
}

function sumYssl() {
    var dhd_data = $('#rksh_dhd_mx').datagrid('getData');
    var sumsssl = 0;
    for (var i = 0; i < dhd_data.rows.length; i++) {
        var sssl = parseFloat(dhd_data.rows[i]['sssl']);
        sssl = isNaN(sssl) ? 0 : sssl;
        sumsssl += sssl;
    }
    return sumsssl;
}